class Election < ActiveRecord::Base

  hobo_model

  has_many :candidates, :dependent => :destroy
  
  has_many :ballots, :dependent => :destroy
  has_many :voters, :class_name => 'User', :through => :ballots, :source => :user
  
  has_many :votes, :dependent => :destroy
  has_many :null_votes, :class_name => 'Vote', :conditions => 'candidate_id IS NULL'  
  
  belongs_to :owner, :class_name => 'User', :foreign_key => 'user_id'

  set_creator_attr :owner
  
  attr_accessible :title, :start_date, :end_date, :public
  
  # --- Validations --- #

  validates_presence_of :start_date, :end_date, :title, :user_id
  validates_uniqueness_of :title
  validates_associated :candidates, :ballots
  validates_length_of :title, :in => 5..128
  validates_inclusion_of :active, :in => [true, false], :allow_nil => true
  validates_inclusion_of :expired, :in => [true, false], :allow_nil => true
  
  def validate_on_create
    if start_date <= Date.today
      errors.add :start_date, "The election must begin in the future"
    end
    if end_date < start_date
      errors.add_to_base "End date must be later than start date"
    end
  end

  # --- Hobo Permissions --- #

  def creatable_by?(creator)
    creator.admin?
  end

  def updatable_by?(updater, new)
    false
  end

  def deletable_by?(deleter)
    false
  end

  def viewable_by?(viewer, field)
    true
  end

  # --- Methods --- #

  def start
    self.active = true
    save!
    #TODO: send mail
  end

  #Ends the current election, and disables all the unused ballots.
  def close
    self.active = false
    self.expired = true
    save!
    ballots.each do |b|
      b.cast = true
      b.save!
      Notifier.deliver_election_end(b.user,title)
    end
  end
  
  def start_if_time
    if !active && !expired && start_date <= Date.today
      start
    end    
  end  
  
  def close_if_time
    if active && end_date < Date.today
      close
    end
  end
  
  def get_results
    
  end

  def expired?  
    expired
  end
end
